<?php
/**
 * It is a basic mysql class to access the database and do some operations.
 */
class BaseMysql {
    private $servername; // the server name or url
    private $username;
    private $password;
    private $dbname; // the DB that you want to connect.
    private $conn; // the resource connecting the DB.
    private $result;
    function __construct($servername, $username, $password, $dbname) {
        $this->servername = $servername != '' ? $servername : "localhost";
        $this->username = $username != '' ? $username : "root";
        $this->password = $password != '' ? $password : "";
        $this->dbname = $dbname != '' ? $dbname : "PHPlesson";
        $this->conn = "";
    }

    /**
     * connect to the database
     * created by wjxu on 2017-02-20T09:41:15+0800
     */
    private function connectToDB() {
        $this->conn = mysql_connect($this->servername, $this->username, $this->password);
        if (!$this->conn) {
            die("Connection failed: " . mysql_connect_error());
            return false;
        } else {
            mysql_select_db($this->dbname, $this->conn);
            mysql_query("SET NAMES 'utf8'");
            return true;
        }
    }

    public function mysqlQueryArr($sql) {
        if (!$this->conn && !$this->connectToDB()) {
            return;
        }
        return mysql_query($sql, $this->conn);
    }

    public function getJsonResult($result, $resultMsg) {
        if ($result) {
            $result = array('resutlCode' => 0, 'resultMsg' => $resultMsg, 'result' => $result);
        } else {
            $result = array('resutlCode' => 1, 'resultMsg' => "Error: " . $sql . "<br>" . mysql_error($this->conn));
        }
        echo json_encode($result);
    }

    public function disconnectToDB() {
        $this->result = "";
        mysql_close($this->conn);
        $this->conn = '';
    }

    public function __get($property_name) {
        if (isset($this->$property_name)) {
            return ($this->$property_name);
        } else {
            return (NULL);
        }
    }

    public function __set($property_name, $value) {
        $this->$property_name = $value;
    }
}
?>